package com.android.library.adapter;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.List;

/**
 * @author xiaoxing
 * Created by pengsheng-2 on 2018/8/29.
 * RecyclerViewAdapter基类
 */

public abstract class BaseAdapter<T> extends RecyclerView.Adapter<ViewHolder> {
    protected ClickItemListener clickItemListener;
    public Context mContext;
    private int mLayoutId;
    protected List<T> mDatas;

    public void setClickItemListener(ClickItemListener clickItemListener) {
        this.clickItemListener = clickItemListener;
    }

    public BaseAdapter(Context mContext, int mLayoutId, List<T> mDatas) {
        this.mContext = mContext;
        this.mLayoutId = mLayoutId;
        this.mDatas = mDatas;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return ViewHolder.get(mContext,parent,mLayoutId);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, final int position) {
        if (mDatas == null || mDatas.size() == 0){
            return;
        }
        convert(holder,mDatas.get(position),position);
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (clickItemListener != null){
                    clickItemListener.clickItem(v,position);
                }
            }
        });
    }

    /**
     * 统一处理
     * @param holder
     * @param t
     * @param position
     */
    public abstract void convert(ViewHolder holder, T t,int position);

    @Override
    public int getItemCount() {
        return mDatas == null ? 0 : mDatas.size();
    }

    @Override
    public long getItemId(int position) {
        return position;
    }
}
